<template>
	<view class="park-list">
		<!-- 搜索栏 -->
		<uni-search-bar v-model="searchValue" placeholder="搜索园区名称" bgColor="#EEEEEE" @confirm="search" />
		<view v-if="filteredParks.length === 0">没有结果</view>
		<view v-else v-for="(parks, initial) in filteredParks" :key="initial">
			<p>{{ initial }}</p>
			<ul>
				<li v-for="park in parks" :key="park.id" @click="add(park)">
					{{ park.username }}
				</li>
			</ul>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		computed
	} from "vue";
	import {
		park,
		users
	} from "@/utils/file.js";
	// 园区列表
	const parksData = reactive({
		parks: [],
		initials: [],
	});

	// 园区列表
	park(uni.getStorageSync('token')).then((res) => {
		const data = res.data.data;
		console.log(res);
		parksData.parks = data;
		parksData.initials = Array.from(new Set(data.map((item) => item.initial))).sort();
	});
	// 搜索数据
	const searchValue = ref('');
	const search = () => {
		uni.showToast({
			title: '搜索：' + searchValue.value,
			icon: 'none'
		})
	};
	// 定义一个计算属性，以根据搜索值筛选公园
	const filteredParks = computed(() => {
		const searchVal = searchValue.value.trim().toLowerCase();
		if (!searchVal) {
			// 如果未输入搜索值，则返回所有园区数据
			const result = {};
			parksData.initials.forEach((initial) => {
				result[initial] = parksData.parks.filter((park) => park.initial === initial);
			});
			return result;
		} else {
			// 根据搜索值过滤园区数据并返回过滤后的结果
			const result = {};
			parksData.initials.forEach((initial) => {
				const filteredParks = parksData.parks.filter(
					(park) =>
					park.initial === initial &&
					park.username.toLowerCase().includes(searchVal)
				);
				if (filteredParks.length > 0) {
					result[initial] = filteredParks;
				}
			});
			return result;
		}
	});
	const input = (res) => {
		console.log('----input:', res)
	};

	function add(park) {
		// 更新用户资料
		users(uni.getStorageSync('token'), park.id).then(res => {
			console.log(res, "更新用户资料", park.id);
		})
 
		setTimeout(() => {
			// 在跳转到其他页面时将园区 ID 作为 URL 参数传递
			uni.reLaunch({
				url: `/pages/index/index?id=${park.id}&name=${park.username}`
			});
		}, 1000)
	}
</script>

<style scoped>
	p {
		font-size: 35rpx;
		color: #7a7a7a;
		height: 50rpx;
		background-color: #e6e6e6;
	}

	ul {
		list-style: none;
		padding: 0;
		margin: 0;
		width: 750rpx;
	}

	li {
		font-size: 34rpx;
		color: #070707;
		margin-bottom: 5px;
		height: 100rpx;
		line-height: 100rpx;
	}

	/* 搜索栏 */
	.search-result {
		padding-top: 10px;
		padding-bottom: 20px;
		text-align: center;
	}

	.search-result-text {
		text-align: center;
		font-size: 14px;
		color: #666;
	}

	.example-body {
		/* #ifndef APP-NVUE */
		display: block;
		/* #endif */
		padding: 0px;
	}

	.uni-mt-10 {
		margin-top: 10px;
	}
</style>